import { createSlice } from '@reduxjs/toolkit';

interface Todo {
  id: number;
  text: string;
  completed: boolean;
}
interface TodoState {
  list: Todo[];
}

const initialState: TodoState = {
  list: [],
};

export const todolistSlice: any = createSlice({
  name: 'todolist',
  initialState,
  reducers: {
    addTodo: (state, action) => {
      console.log('action', action);
      state.list.push(action.payload);
    },
    delTodo: (state, acttion) => {
      state.list = state.list.filter((item) => item.id !== acttion.payload);
    },
    finishTodo: (state, action) => {
      const todo = state.list.find((item) => {
        return item.id === action.payload;
      });
      if (todo) {
        todo.completed = !todo.completed;
      }
    },
  },
});

export const todolist_list = (state: any) => {
  return state.todolist.list;
};
export const todolist_completed = (state: any) => {
  return state.todolist.completed;
};

export const { addTodo, delTodo, finishTodo } = todolistSlice.actions;

export default todolistSlice.reducer;
